package com.sy.simpleegg

import android.annotation.SuppressLint
import android.os.Environment
import androidx.lifecycle.lifecycleScope
import com.sy.simpleegg.base.BaseMvpActivity
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.databinding.ActivityUpgradeBinding
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.onClick
import com.sy.simpleegg.mvp.contract.UpgradeContract
import com.sy.simpleegg.mvp.presenter.UpgradePresenter
import com.sy.simpleegg.util.BoardApiUtil
import com.sy.simpleegg.util.DateTimeUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 * @author sy
 * @date 2024/10/26 15:27
 * @desc
 */
class UpgradeActivity :
    BaseMvpActivity<UpgradeContract.View, UpgradeContract.Presenter, ActivityUpgradeBinding>(),
    UpgradeContract.View{

        private var failedCount = 0
    private var url: String? = null
    private var verName = ""
    private var lastClickTime: Long = 0L
    private var curClickTime: Long = 0L
    private var clickCount: Int = 1

    override fun createPresenter(): UpgradeContract.Presenter = UpgradePresenter(lifecycleScope)

    override fun getViewBinding(): ActivityUpgradeBinding = ActivityUpgradeBinding.inflate(layoutInflater)

    override fun attachLayoutRes(): Int = R.layout.activity_upgrade

    override fun useEventBus(): Boolean {
        return false
    }

    override fun initData() {

    }

    override fun initOther() {
        binding.btnExit.onClick(gap = 0) {
            exitApp()
        }

        intent.run {
            url = getStringExtra("downloadUrl")
            verName = getStringExtra("verName")?: DateTimeUtil.nowDateTime
        }

        url?.let {
            startDownload()
        }
    }

    override fun refreshProgress(progress: Int) {
        binding.pb.progress = progress
    }

    override fun downloadSuccess(path: String) {
        logFile("下载成功，开始安装APK：$path")
        BoardApiUtil.installSilence(path)
    }

    @SuppressLint("SetTextI18n")
    override fun failed(msg: String) {
        try {
            failedCount ++
            if (failedCount < 3){
                binding.tvUpdateTips.text = "更新失败"
                lifecycleScope.launch {
                    delay(2000)
                    startDownload()
                }
            }else{
                lifecycleScope.launch {
                    repeat(3){ count ->
                        binding.tvUpdateTips.text = "更新失败，${count}秒后重启系统"
                        delay(1000)
                    }
                    BoardApiUtil.rebootSystem()
                }
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("下载APP失败后，处理异常：${e.message}")
        }
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    private fun startDownload(){
        lifecycleScope.launch {
            try {
                binding.pb.progress = 0
                binding.tvUpdateTips.text = "系统更新中"
                val diskPath = Environment.getExternalStorageDirectory().absolutePath
                val apkName = "${DateTimeUtil.nowDateTimeSp}.apk"
                val savePath = diskPath + File.separatorChar + "whm_download" + File.separatorChar + verName
                mPresenter?.downloadApp(savePath, apkName, url!!)
            }catch (e: Exception){
                e.printStackTrace()
                logFile("开始下载APP异常：${e.message}")
            }
        }
    }

    private fun exitApp(){
        lastClickTime = curClickTime
        curClickTime = System.currentTimeMillis()
        if (curClickTime - lastClickTime < 500) {
            clickCount++
            if (clickCount >= Constant.KEYBOARD_CLICK_COUNT) {
                clickCount = 1
                exit()
            }
        } else {
            clickCount = 1
        }
    }

}